import { isDebugMode } from '@/config/public'
import axios from 'axios'
import Cookie from 'js-cookie'

// import { Base64 } from 'js-base64'

// 跨域认证信息 header 名
const xsrfHeaderName = 'Access-Token'

axios.defaults.timeout = 15000
axios.defaults.withCredentials = true
// axios.defaults.xsrfHeaderName = ''
axios.defaults.xsrfCookieName = xsrfHeaderName

// 认证类型
const AUTH_TYPE = {
  BEARER: 'Bearer',
  BASIC: 'basic',
  AUTH1: 'auth1',
  AUTH2: 'auth2'
}

// http method
const METHOD = {
  GET: 'get',
  GET_PARAM_ARRAY: 'get_param_array',
  POST: 'post',
  POST_JSON: 'post_json',
  POST_JSON_ENCRYPT: 'post_json_encrypt',
  POST_FORM: 'post_form',
  DELETE: 'delete',
  DELETE_JSON: 'delete_json',
  DELETE_JSON_ENCRYPT: 'delete_json_encrypt',
  PUT: 'put',
  PUT_JSON: 'put_json',
  PUT_JSON_ENCRYPT: 'put_json_encrypt'
}

/**
 * axios请求
 * @param url 请求地址
 * @param method {METHOD} http method
 * @param params 请求参数
 * @returns {Promise<AxiosResponse<T>>}
 */
async function request(
  url,
  method,
  params,
  cfg = { responseType: '', timeout: axios.defaults.timeout, isNeedToken: true }
) {
  if (isDebugMode) {
    console.log(
      '%c REQUEST => ',
      'background: #222; color: #bada55',
      `[url]: ${url}`,
      `[method]: ${method}`,
      `[params]:`,
      params,
      cfg
    )
  }

  params = paramsFilter(params)
  switch (method) {
    case METHOD.GET:
      return axios.get(url, {
        params,
        responseType: cfg.responseType,
        timeout: cfg.timeout,
        isNeedToken: cfg.isNeedToken
      })
    case METHOD.GET_PARAM_ARRAY: {
      const temp = new URLSearchParams()
      if (params) {
        for (const key in params) {
          if (params[key]) {
            const element = params[key]
            if (Array.isArray(element)) {
              for (const v of element) {
                temp.append(key, v)
              }
            } else {
              temp.append(key, element)
            }
          }
        }
      }
      return axios.get(url, {
        params: temp,
        responseType: cfg.responseType,
        timeout: cfg.timeout,
        isNeedToken: cfg.isNeedToken
      })
    }
    case METHOD.POST:
      return axios.post(url, params, {
        responseType: cfg.responseType,
        timeout: cfg.timeout,
        isNeedToken: cfg.isNeedToken
      })
    case METHOD.POST_JSON:
      return axios.post(url, params, {
        headers: {
          'Content-Type': 'application/json'
        },
        responseType: cfg.responseType,
        timeout: cfg.timeout,
        isNeedToken: cfg.isNeedToken
      })
    case METHOD.POST_JSON_ENCRYPT:
      // Base64.encode(JSON.stringify(params))
      return axios.post(url, params ? JSON.stringify(params) : null, {
        headers: {
          'Content-Type': 'application/json'
        },
        responseType: cfg.responseType,
        timeout: cfg.timeout,
        isNeedToken: cfg.isNeedToken
      })
    case METHOD.POST_FORM:
      return axios.post(url, params ? params : null, {
        headers: {
          'Content-Type': 'multipart/form-data'
        },
        responseType: cfg.responseType,
        timeout: cfg.timeout,
        isNeedToken: cfg.isNeedToken
      })
    case METHOD.DELETE:
      return axios.delete(url, params)
    case METHOD.DELETE_JSON:
      return axios.delete(
        url,
        params
          ? {
              data: JSON.stringify(params),
              headers: {
                'Content-Type': 'application/json'
              },
              isNeedToken: cfg.isNeedToken
            }
          : null
      )
    case METHOD.DELETE_JSON_ENCRYPT:
      // Base64.encode(JSON.stringify(params))
      return axios.delete(
        url,
        params
          ? {
              data: JSON.stringify(params),
              headers: {
                'Content-Type': 'application/json'
              }
            }
          : null
      )
    case METHOD.PUT:
      return axios.put(url, params, {
        responseType: cfg.responseType,
        timeout: cfg.timeout,
        isNeedToken: cfg.isNeedToken
      })
    case METHOD.PUT_JSON:
      return axios.put(url, params, {
        headers: {
          'Content-Type': 'application/json'
        },
        responseType: cfg.responseType,
        timeout: cfg.timeout,
        isNeedToken: cfg.isNeedToken
      })
    case METHOD.PUT_JSON_ENCRYPT:
      // Base64.encode(JSON.stringify(params))
      return axios.put(url, params ? JSON.stringify(params) : null, {
        headers: {
          'Content-Type': 'application/json'
        },
        responseType: cfg.responseType,
        timeout: cfg.timeout,
        isNeedToken: cfg.isNeedToken
      })
    default:
      return axios.get(url, {
        params,
        responseType: cfg.responseType,
        timeout: cfg.timeout,
        isNeedToken: cfg.isNeedToken
      })
  }
}

/**
 * filter invalid params
 * @param {Object} params
 */
function paramsFilter(params) {
  if (params && typeof params === 'object' && !(params instanceof FormData)) {
    params = JSON.parse(JSON.stringify(params))
    if (!Array.isArray(params)) {
      let invalidKeys = []
      for (const key in params) {
        const v = params[key]
        if (v === null || (typeof v === 'string' && v.trim() === '')) {
          invalidKeys.push(key)
        }
      }
      for (const key of invalidKeys) {
        delete params[key]
      }
    }
    if (isDebugMode) {
      console.log(`[valid-params]:`, params)
    }
  }
  return params
}

/**
 * 设置认证信息
 * @param auth {Object}
 * @param authType {AUTH_TYPE} 认证类型，默认：{AUTH_TYPE.BEARER}
 */
function setAuthorization(auth, authType = AUTH_TYPE.BEARER) {
  switch (authType) {
    case AUTH_TYPE.BEARER:
      Cookie.set(xsrfHeaderName, auth.token, { expires: auth.expireAt })
      break
    case AUTH_TYPE.BASIC:
    case AUTH_TYPE.AUTH1:
    case AUTH_TYPE.AUTH2:
    default:
      break
  }
}

/**
 * 移出认证信息
 * @param authType {AUTH_TYPE} 认证类型
 */
function removeAuthorization(authType = AUTH_TYPE.BEARER) {
  switch (authType) {
    case AUTH_TYPE.BEARER:
      Cookie.remove(xsrfHeaderName)
      break
    case AUTH_TYPE.BASIC:
    case AUTH_TYPE.AUTH1:
    case AUTH_TYPE.AUTH2:
    default:
      break
  }
}

/**
 * 检查认证信息
 * @param authType
 * @returns {boolean}
 */
function checkAuthorization(authType = AUTH_TYPE.BEARER) {
  switch (authType) {
    case AUTH_TYPE.BEARER:
      if (Cookie.get(xsrfHeaderName)) {
        return true
      }
      break
    case AUTH_TYPE.BASIC:
    case AUTH_TYPE.AUTH1:
    case AUTH_TYPE.AUTH2:
    default:
      break
  }
  return false
}

/**
 * kv cookie存储
 * @param {string} key
 * @param {string} value
 */
function setCookie(key, value) {
  Cookie.set(key, value)
}

/**
 * ger value from cookie
 * @param {string} key
 */
function getCookie(key) {
  return Cookie.get(key)
}

/**
 * 加载 axios 拦截器
 * @param interceptors
 * @param options
 */
function loadInterceptors(interceptors, options) {
  const { request, response } = interceptors
  // 加载请求拦截器
  request.forEach(item => {
    let { onFulfilled, onRejected } = item
    if (!onFulfilled || typeof onFulfilled !== 'function') {
      onFulfilled = config => config
    }
    if (!onRejected || typeof onRejected !== 'function') {
      onRejected = error => Promise.reject(error)
    }

    // axios.interceptors.request.use(
    //   config => onFulfilled(config, options),
    //   error => onRejected(error, options)
    // )
    axios.interceptors.request.use(
      config => {
        // console.log('request===============config===================', config)
        return onFulfilled(config, options)
      },
      error => {
        // console.log('request===============error===================', error)
        return onRejected(error, options)
      }
    )
  })
  // 加载响应拦截器
  response.forEach(item => {
    let { onFulfilled, onRejected } = item
    if (!onFulfilled || typeof onFulfilled !== 'function') {
      onFulfilled = response => response
    }
    if (!onRejected || typeof onRejected !== 'function') {
      onRejected = error => Promise.reject(error)
    }
    // axios.interceptors.response.use(
    //   response => onFulfilled(response, options),
    //   error => onRejected(error, options)
    // )
    axios.interceptors.response.use(
      response => {
        // console.log(
        //   'response===============config===================',
        //   response
        // )
        return onFulfilled(response, options)
      },
      error => {
        // console.log('response===============error===================', error)
        return onRejected(error, options)
      }
    )
  })
}

/**
 * 解析 url 中的参数
 * @param url
 * @returns {Object}
 */
function parseUrlParams(url) {
  const params = {}
  if (!url || url === '' || typeof url !== 'string') {
    return params
  }
  const paramsStr = url.split('?')[1]
  if (!paramsStr) {
    return params
  }
  const paramsArr = paramsStr.replace(/&|=/g, ' ').split(' ')
  for (let i = 0; i < paramsArr.length / 2; i++) {
    const value = paramsArr[i * 2 + 1]
    params[paramsArr[i * 2]] =
      value === 'true' ? true : value === 'false' ? false : value
  }
  return params
}

export {
  METHOD,
  AUTH_TYPE,
  request,
  setAuthorization,
  removeAuthorization,
  checkAuthorization,
  setCookie,
  getCookie,
  loadInterceptors,
  parseUrlParams
}
